package net.caixiaomi.info.shopkeeper;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.sobot.chat.utils.ScreenUtils;

import net.caixiaomi.info.R;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.permissions.Permission;
import net.caixiaomi.info.base.permissions.RxPermissions;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.life.BaseDialog;
import net.caixiaomi.info.life.EWMDialog;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.shopkeeper.adapter.ShopDetailAdapter;
import net.caixiaomi.info.shopkeeper.entity.ShopDetailEntity;
import net.caixiaomi.info.shopkeeper.entity.ShopDetailMainEntity;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.FileHelper;
import net.caixiaomi.info.util.ToastUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import io.reactivex.functions.Consumer;
import retrofit2.Call;

/**
 * Created by mac on 2018/11/14.
 */

public class ShopPhotoDialog extends BaseDialog implements View.OnClickListener{

    private static final int CODE_CAMERA_REQUEST = 1000;
    private static final int CODE_RESULT_REQUEST = 1002;
    private String mContent;
    private ImageView mImgIv;
    private ImageView mDeleteIv;
    private RelativeLayout mPhotoGroup;
    private LinearLayout mAddGroup;
    private RelativeLayout mFailureGroup;
    private RelativeLayout mEnsureGroup;
    private LinearLayout mListGroup;
    private TextView mTitle;
    private ImageView mTitleImg;
    private TextView mEnsureTv;
    private Context mContext;
    private Uri mImageUri;

    private callBack mCallBack;

    private boolean mHasPhoto=false;

    RecyclerView mListView;
    private ShopDetailAdapter mAdapter;
    private ShopDetailMainEntity shopDetailMainEntity;
    private ShopDetailEntity mEntity;

    private CircularProgressBar mProgress;

    public ShopPhotoDialog(@NonNull Context context,callBack callBack) {
        super(context);
        mCallBack=callBack;
        mContext=context;
    }

    interface callBack{
        public void setPhoto(Intent intent,int requestCode);
        public void success();
        public void failure();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shop_order_dialog_layout);
        mProgress=findViewById(R.id.progress);
        mProgress.setVisibility(View.GONE);
        mTitle=findViewById(R.id.shop_order_title_name);
        mTitleImg=findViewById(R.id.shop_order_title_img);
        mImgIv=findViewById(R.id.shop_photo_iv);
        mListGroup=findViewById(R.id.dia_list_group);
        mDeleteIv=findViewById(R.id.shop_delete_img);
        mPhotoGroup=findViewById(R.id.shop_photo_layout);
        mFailureGroup=findViewById(R.id.shop_failure_layout);
        mEnsureGroup=findViewById(R.id.shop_ensure_layout);
        mEnsureTv=findViewById(R.id.shop_ensure_tv);
        mAddGroup=findViewById(R.id.shop_add_rl);
        mListView=findViewById(R.id.shop_listview);
        mAddGroup.setOnClickListener(this);
        mImgIv.setOnClickListener(this);
        mDeleteIv.setOnClickListener(this);
        mEnsureGroup.setOnClickListener(this);
        mFailureGroup.setOnClickListener(this);
//        mEnsureGroup.setClickable(false);
        mTitleImg.setOnClickListener(this);
//        mEnsureTv.setOnClickListener(this);
        mFailureGroup.setOnClickListener(this);

        setCanceledOnTouchOutside(true);
        setGravity(Gravity.CENTER,23,0);
        setLayoutParams(CommonApp.mScreenWidth- ScreenUtils.dip2px(mContext,30),CommonApp.mScreenHeight-ScreenUtils.dip2px(mContext,100));

        mListView.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new ShopDetailAdapter(null);
        mListView.setAdapter(mAdapter);
        View headerView=View.inflate(mContext,R.layout.shop_order_top_layout,null);
        mAdapter.addHeaderView(headerView);

        mListView.post(new Runnable() {
            @Override
            public void run() {
//                int measureHeight=mListView.getMeasuredHeight();
//                int bb=mListGroup.getMeasuredHeight();
//                String aaa="";
//                setLayoutParams(CommonApp.mScreenWidth- ScreenUtils.dip2px(mContext,30),ScreenUtils.dip2px(mContext,100));
            }
        });
        initDetail();
        initStatus();
    }

    Bitmap photo=null;
    String picPath;

    public void setShopEntity(ShopDetailMainEntity entity){
        shopDetailMainEntity=entity;
        mEntity=entity.getDetail();
    }

    private void initStatus(){
        if(shopDetailMainEntity.getShopStatus()==0){
            findViewById(R.id.shop_setting_dia).setVisibility(View.VISIBLE);
            findViewById(R.id.shop_his_group).setVisibility(View.GONE);
        }else{
            ImageView photoImg=findViewById(R.id.shop_his_img);
            Glide.with(mContext).load(shopDetailMainEntity.getPhotpee().getTicketPicUrl()).into(photoImg);
            if(!TextUtils.isEmpty(shopDetailMainEntity.getPhotpee().getTicketPicUrl())){
                photoImg.setOnClickListener(this);
                photoImg.setTag(R.id.shop_his_img,shopDetailMainEntity.getPhotpee().getTicketPicUrl());
            }

            findViewById(R.id.shop_setting_dia).setVisibility(View.GONE);
            findViewById(R.id.shop_his_group).setVisibility(View.VISIBLE);
            TextView his0=findViewById(R.id.shop_his_tv0);
            his0.setText(shopDetailMainEntity.getPhotpee().getTicketStatus().equals("1")?"出票成功":"出票失败");
            TextView his1=findViewById(R.id.shop_his_tv1);
            his1.setText(shopDetailMainEntity.getPhotpee().getPicAddTime());
            TextView his2=findViewById(R.id.shop_his_tv2);
            his2.setVisibility(View.GONE);
            if(!shopDetailMainEntity.getPhotpee().getTicketStatus().equals("1")){
                if(!shopDetailMainEntity.getPhotpee().getFailReason().equals("")){
                    his2.setText("备注: "+shopDetailMainEntity.getPhotpee().getFailReason());
                    his2.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    private void initDetail(){
        if(mEntity!=null){
            for(int i=0;i<mEntity.getOrderDetailDto().getMatchInfos().size();i++){
                mEntity.getOrderDetailDto().getMatchInfos().get(i).setItemType(Constants.ITEM_MATCH_LIVE1);
            }
            mAdapter.addData(mEntity.getOrderDetailDto().getMatchInfos());
            mAdapter.addData(mEntity.getOrderDetailDto());
            mAdapter.addData(mEntity.getTicketSchemeDTO().getTicketSchemeDetailDTOs());

            mTitle.setText("订单编号: "+mEntity.getOrderDetailDto().getOrderSn());
        }
    }

    /**
     * 销毁图片文件
     */
    private void destoryBimap()
    {
        if (photo != null && ! photo.isRecycled()) {
            photo.recycle();
            photo = null;
        }
    }

    public void setData(Intent data){
        mPhotoGroup.setVisibility(View.VISIBLE);
        mAddGroup.setVisibility(View.GONE);

        Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                "cxm"+ ".jpg"));

        if (uri != null) {
            this.photo = BitmapFactory.decodeFile(uri.getPath());
        }





        Bitmap bitmap = photo;
        File myCaptureFile1 = null;
        try {
            myCaptureFile1 = new File(Environment.getExternalStorageDirectory(), "/temp/" + "picc_" + ".jpg");
            if (!myCaptureFile1.getParentFile().exists())
                myCaptureFile1.getParentFile().mkdirs();

            BufferedOutputStream bos1 = null;
            bos1 = new BufferedOutputStream(new FileOutputStream(
                    myCaptureFile1));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 30, bos1);
            bos1.flush();
            bos1.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        PhotoImpl.uploadFilePath=myCaptureFile1.getAbsolutePath();



        FileOutputStream fileOutputStream = null;
        File file=FileHelper.getOutputMediaFile();
        // 打开文件输出流
        try {
            fileOutputStream = new FileOutputStream(file);
            // 生成图片文件
            this.photo.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            // 相片的完整路径
            this.picPath = file.getAbsolutePath();

            Glide.with(mContext).load(photo).into(mImgIv);
            mHasPhoto=true;

            mEnsureGroup.setBackgroundResource(R.drawable.btn_orange_corner);

//            PhotoImpl.uploadFilePath=file.getAbsolutePath();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.shop_his_img:
                String url= (String) view.getTag(R.id.shop_his_img);
                Intent imgIntent = new Intent(mContext,
                        ImgScanActivity.class);
                String[] imageid = new String[] { url };
                imgIntent.putExtra(ImgScanActivity.KEY_IMAGE_ID, imageid);
                imgIntent.putExtra("edite", "show.choose.icon.dialog");
                mContext.startActivity(imgIntent);
                break;
            case R.id.shop_photo_iv:
                Intent imgIntent1 = new Intent(mContext,
                        ImgScanActivity.class);
                String[] imageid1 = new String[] { "" };
                imgIntent1.putExtra(ImgScanActivity.KEY_IMAGE_ID, imageid1);
                imgIntent1.putExtra("edite", "show.choose.icon.dialog");
                mContext.startActivity(imgIntent1);
                break;
            case R.id.shop_add_rl:
                checkPermissionAndTakePicture();
                break;
            case R.id.shop_delete_img:
                mHasPhoto=false;
                mEnsureGroup.setBackgroundResource(R.drawable.btn_shadow_gray__corner);
                mPhotoGroup.setVisibility(View.GONE);
                mAddGroup.setVisibility(View.VISIBLE);
                break;
            case R.id.shop_order_title_img:
                dismiss();
                break;
            case R.id.shop_failure_layout:
                final ShopFailureDialog dialog=new ShopFailureDialog(mContext, new ShopFailureDialog.callBack() {

                    @Override
                    public void failure(String failMsg) {
                        failureModify(failMsg);
                    }
                });
                dialog.show();
                dialog.setCancelable(true);
                break;
            case R.id.shop_ensure_layout:
                if(mHasPhoto) {
                    modify();
                }
                break;
        }
    }

    private void checkPermissionAndTakePicture() {
        RxPermissions mRxPermissions = new RxPermissions((Activity) mContext);
        mRxPermissions
                .requestEach(
                        Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            if (TextUtils.equals(permission.name, Manifest.permission.CAMERA)) {
                                destoryBimap();
                                String state = Environment.getExternalStorageState();
                                if (state.equals(Environment.MEDIA_MOUNTED)) {
//                                    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                    Uri take_pic_uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                                             "cxm"+ ".jpg"));
                                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, take_pic_uri);

                                    mCallBack.setPhoto(intent, CODE_CAMERA_REQUEST);
                                } else {
                                }
                            }
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                        } else {
                            // 用户拒绝了该权限，并且选中『不再询问』
                        }
                    }
                });
    }

    private void modify(){
        mProgress.setVisibility(View.VISIBLE);
        PhotoImpl impl=new PhotoImpl();
        impl.init(mContext, new PhotoImpl.callBack() {
            @Override
            public void onSuccess(String path) {
                JSONObject params = new JSONObject();
                params.put("orderSn", mEntity.getOrderDetailDto().getOrderSn());
                params.put("orderStatus", 1);
                String top=PhotoImpl.endpoint;
                top=top.replace("http://","http://"+PhotoImpl.testBucket+".");
                params.put("picUrl", top+"/"+PhotoImpl.uploadObject);
                RequestService requestService = RetrofitManage.getInstance().getRequestService();
                Call<BaseCallModel> modify = requestService.modifyXN(params);
                modify.enqueue(new ResponseCallback<BaseCallModel>() {
                    @Override
                    public void onSuccess(BaseCallModel data) {
                        ToastUtil.s("出票成功");
                        mCallBack.success();
                        mProgress.setVisibility(View.GONE);
                        dismiss();
                    }

                    @Override
                    public void onFail(ResponseError error) {
                        ToastUtil.s(error.getMessage());
                        mProgress.setVisibility(View.GONE);
                    }

                    @Override
                    public void onError() {
                        ToastUtil.s("网络异常");
                        mProgress.setVisibility(View.GONE);
                    }
                });
            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.s(msg);
            }
        });
        impl.loadImg();
    }

    private void failureModify(final String failMsg){
        mProgress.setVisibility(View.VISIBLE);

        String photoUrl="";
        if(mHasPhoto){
            String top=PhotoImpl.endpoint;
            top=top.replace("http://","http://"+PhotoImpl.testBucket+".");
            photoUrl=top+"/"+PhotoImpl.uploadObject;
            PhotoImpl impl=new PhotoImpl();
            final String finalPhotoUrl = photoUrl;
            impl.init(mContext, new PhotoImpl.callBack() {

                @Override
                public void onSuccess(String path) {
                    modifyFialure(failMsg, finalPhotoUrl);
                    mProgress.setVisibility(View.GONE);
                }

                @Override
                public void onFailure(String msg) {
                    ToastUtil.s(msg);
                    mProgress.setVisibility(View.GONE);
                }

            });
            impl.loadImg();
        }else{
            modifyFialure(failMsg, "");
        }


//        PhotoImpl impl=new PhotoImpl();
//        impl.init(mContext, new PhotoImpl.callBack() {
//            @Override
//            public void onSuccess(String path) {
//
//                JSONObject params = new JSONObject();
//                params.put("failMsg", failMsg);
//                params.put("orderSn", mEntity.getOrderDetailDto().getOrderSn());
//                params.put("orderStatus", 2);
//                if(mHasPhoto){
//                    String top=PhotoImpl.endpoint;
//                    top=top.replace("http://","http://"+PhotoImpl.testBucket+".");
//                    params.put("picUrl",top+"/"+PhotoImpl.uploadObject);
//                }
//                RequestService requestService = RetrofitManage.getInstance().getRequestService();
//                Call<BaseCallModel> modify = requestService.modifyXN(params);
//                modify.enqueue(new ResponseCallback<BaseCallModel>() {
//                    @Override
//                    public void onSuccess(BaseCallModel data) {
//                        mCallBack.failure();
//                        ToastUtil.s("出票失败");
//                        dismiss();
//                    }
//
//                    @Override
//                    public void onFail(ResponseError error) {
//                        mCallBack.failure();
//                        ToastUtil.s(error.getMessage());
//                    }
//
//                    @Override
//                    public void onError() {
//                        mCallBack.failure();
//                        ToastUtil.s("网络异常");
//                    }
//                });
//            }
//
//            @Override
//            public void onFailure(String msg) {
//                ToastUtil.s(msg);
//            }
//        });
//        impl.loadImg();
    }


    private void modifyFialure(String failMsg,String url){
        JSONObject params = new JSONObject();
        params.put("failMsg", failMsg);
        params.put("orderSn", mEntity.getOrderDetailDto().getOrderSn());
        params.put("orderStatus", 2);
        if(mHasPhoto){
            params.put("picUrl",url);
        }
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel> modify = requestService.modifyXN(params);
        modify.enqueue(new ResponseCallback<BaseCallModel>() {
            @Override
            public void onSuccess(BaseCallModel data) {
                mCallBack.failure();
                ToastUtil.s("出票失败");
                dismiss();
                mProgress.setVisibility(View.GONE);
            }

            @Override
            public void onFail(ResponseError error) {
                mCallBack.failure();
                ToastUtil.s(error.getMessage());
                mProgress.setVisibility(View.GONE);
            }

            @Override
            public void onError() {
                mCallBack.failure();
                ToastUtil.s("网络异常");
                mProgress.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 读取图片属性：旋转的角度
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree  = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }
    /*
     * 旋转图片
     * @param angle
     * @param bitmap
     * @return Bitmap
     */
    public static Bitmap rotaingImageView(int angle , Bitmap bitmap) {
        //旋转图片 动作
        Matrix matrix = new Matrix();;
        matrix.postRotate(angle);
        System.out.println("angle2=" + angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }
}
